﻿package com.task.common;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;

public class BaseHibernateDao <T> {
	@Resource
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	/**
	 * 获取session
	 * @return
	 */
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	/**
	 * 获取父类泛型类型
	 * @return
	 */
	private Class getSuperClassGenericType(){
		Type genType = this.getClass().getGenericSuperclass();
		if(!(genType instanceof ParameterizedType)){
			return Object.class;
		}
		
		Type[] types = ((ParameterizedType)genType).getActualTypeArguments();
		
		return (Class) types[0];
	}
	
	/**
	 * 添加操作
	 * @param entity
	 * @return
	 */
	public Serializable add(T entity){
		Session session = sessionFactory.getCurrentSession();
		return session.save(entity);
	}
	/**
	 * 更新操作
	 * @param entity
	 * @return
	 */
	public void update(T entity){
		Session session = sessionFactory.getCurrentSession();
		session.update(entity);
	}
	/**
	 * 根据主键编号删除元素
	 * @param id
	 */
	public void deleteById(Serializable id){
		Session session = sessionFactory.getCurrentSession();
		Object o = session.get(getSuperClassGenericType(), id);
		if(o != null){
			session.delete(o);
		}
	}
	/**
	 * 根据编号查询单个对象
	 * @param id
	 * @return
	 */
	public T getById(Serializable id){
		Session session = sessionFactory.getCurrentSession();
		return (T) session.get(getSuperClassGenericType(), id);
	}
	
	/**
	 * 分页查询数据
	 * @param pageNo 当前页
	 * @param pageSize 每页显示数据条数
	 * @return
	 */
	public List<T> getPageList(int pageNo, int pageSize){
		Session session = sessionFactory.getCurrentSession();
		String hql = "from " + getSuperClassGenericType().getSimpleName();
		Query query = session.createQuery(hql);		
		int start = (pageNo - 1)* pageSize;
		query.setFirstResult(start);
		query.setMaxResults(pageSize);
		
		return query.list();
	}
	
	/**
	 * 获取总数据条数
	 * @return
	 */
	public int getCountOfEntity(){
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(getSuperClassGenericType());
		
		criteria.setProjection(Projections.rowCount());
		return Integer.parseInt(criteria.uniqueResult().toString());
	}
}
